package com.cfh.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import org.apache.log4j.Logger;
import org.springframework.util.Assert;

import com.cfh.ahead.Constant;
import com.cfh.ahead.IdcardValidator;
import com.cfh.ahead.Logic;
import com.cfh.ahead.LogicItem;
import com.cfh.ahead.SequenceNameProvider;
import com.cfh.domain.Answer;
import com.cfh.domain.AnswerExample;
import com.cfh.domain.Config;
import com.cfh.domain.ConfigExample;
import com.cfh.domain.ConfigKey;
import com.cfh.domain.Product;
import com.cfh.domain.ProductExample;
import com.cfh.domain.Sequence;
import com.cfh.persistence.dao.AnswerDAO;
import com.cfh.persistence.dao.ConfigDAO;
import com.cfh.persistence.dao.ProductDAO;
import com.cfh.persistence.dao.SequenceDAO;
import com.cfh.util.Tools;
import com.cfh.util.XmlStringBuffer;

public class XmlServiceImpl implements XmlService {

	private ProductDAO productDAO;
	private ConfigDAO configDAO;
	private AnswerDAO answerDAO;
	private SequenceDAO sequenceDAO;
	private SequenceNameProvider sequenceNameProvider;

	private static final Logger logger = Logger.getLogger(XmlServiceImpl.class);

	public String selectAllProduct() {
		XmlStringBuffer xsb = new XmlStringBuffer();
		List prdExtList = null;
		List prdList = null;
		List langList = null;
		int langCount = 0;
		List companyList = null;
		int companyCount = 0;
		try {
			{// get all prds
				ProductExample prdExample = new ProductExample();
				prdExample.createCriteria();
				prdList = productDAO.selectByExample(prdExample);
			}
			{// get prd extentions
				ConfigExample configExample = new ConfigExample();
				List cfgTypes = new ArrayList();
				cfgTypes.add(Constant.CFG_TYPE_FLV);
				cfgTypes.add(Constant.CFG_TYPE_PDF);
				cfgTypes.add(Constant.CFG_TYPE_BUYURL);
				cfgTypes.add(Constant.CFG_TYPE_INTRO);
				configExample.createCriteria().andCFG_TYPEIn(cfgTypes);
				prdExtList = configDAO.selectByExample(configExample);
			}
			{// get langs
				ConfigExample configExample = new ConfigExample();
				configExample.createCriteria().andCFG_TYPEEqualTo(Constant.CFG_TYPE_LANG);
				configExample.setOrderByClause(Constant.ORDERBY_LANG);
				langList = configDAO.selectByExample(configExample);
				langCount = langList.size();
				logger.debug("langCount:" + langCount);
			}
			{// get companys
				ConfigExample configExample = new ConfigExample();
				configExample.createCriteria().andCFG_TYPEEqualTo(Constant.CFG_TYPE_COMPANY);
				configExample.setOrderByClause(Constant.ORDERBY_COMPANY);
				companyList = configDAO.selectByExample(configExample);
				companyCount = companyList.size();
				logger.debug("companyCount:" + companyCount);
			}

			if (Constant.XML_HEAD_ISUSED) {
				xsb.appendOriginal(Constant.XML_HEAD_STRING);
			}
			xsb.startTag("datas");
			xsb.startTag("languages");
			for (int i = 0; i < langCount; i++) {

				Config tmpLangCfg = (Config) langList.get(i);
				xsb.startTagWithNameId("language", tmpLangCfg.getCFG_VALUE(), tmpLangCfg.getCFG_CODE());
				xsb.appendEscape(tmpLangCfg.getCFG_VALUE());
				xsb.endTag("language");
			}
			xsb.endTag("languages");

			for (Iterator iterator = prdList.iterator(); iterator.hasNext();) {

				Product prd = (Product) iterator.next();
				xsb.startTagWithNameIdShowflag("data", prd.getPRD_SHORT(), prd.getPRD_CODE(), prd.getSHOW_FLG());
				
				xsb.startTagWithName("title", "全名");
				xsb.appendEscape(prd.getPRD_NAME());
				xsb.endTag("title");
				
				xsb.startTagWithName("message", "简介"); 
				xsb.appendEscape(prd.getPRD_DESC());
				xsb.endTag("message");
				
				xsb.startTagWithName("pic", "产品图标"); 
				xsb.appendEscape(prd.getPRD_PIC());
				xsb.endTag("pic");
				
				xsb.startTagWithName("swfList", "动画");
				for (int i = 0; i < langCount; i++) {
					Config tmpLangCfg = (Config) langList.get(i);
					String tmpLang = tmpLangCfg.getCFG_CODE();
					xsb.startTagWithName("language", tmpLangCfg.getCFG_VALUE());
					String content = getFlv(prdExtList, prd, tmpLang);
					xsb.appendEscape(content);
					xsb.endTag("language");
				}
				xsb.endTag("swfList");
				

				xsb.startTagWithName("buyList", "直接购买");
				for (int i = 0; i < langCount; i++) {

					Config tmpLangCfg = (Config) langList.get(i);
					String tmpLang = tmpLangCfg.getCFG_CODE();
					xsb.startTagWithName("language", tmpLangCfg.getCFG_VALUE());
					for (int j = 0; j < companyCount; j++) {
						Config tmpCompanyCfg = (Config) companyList.get(j);
						String tmpCompany = tmpCompanyCfg.getCFG_CODE();
						String content = getBuyUrl(prdExtList, prd, tmpLang, tmpCompany);
						xsb.startTagWithName("data", tmpCompanyCfg.getCFG_VALUE());
						xsb.appendEscape(content);
						xsb.endTag("data");
					}
					xsb.endTag("language");
				}
				xsb.endTag("buyList");

				xsb.startTagWithName("pdfList", "PDF下载");
				for (int i = 0; i < langCount; i++) {
					Config tmpLangCfg = (Config) langList.get(i);
					String tmpLang = tmpLangCfg.getCFG_CODE();
					xsb.startTagWithName("language", tmpLangCfg.getCFG_VALUE());
					for (int j = 0; j < companyCount; j++) {
						Config tmpCompanyCfg = (Config) companyList.get(j);
						String tmpCompany = tmpCompanyCfg.getCFG_CODE();
						String content = getPdfUrl(prdExtList, prd, tmpLang, tmpCompany);
						xsb.startTagWithName("data", tmpCompanyCfg.getCFG_VALUE());
						xsb.appendEscape(content);
						xsb.endTag("data");
					}
					xsb.endTag("language");
				}
				xsb.endTag("pdfList");

				xsb.startTagWithName("introList", "产品详细");
				for (int i = 0; i < langCount; i++) {
					Config tmpLangCfg = (Config) langList.get(i);
					String tmpLang = tmpLangCfg.getCFG_CODE();
					xsb.startTagWithName("language", tmpLangCfg.getCFG_VALUE());
					for (int j = 0; j < companyCount; j++) {
						Config tmpCompanyCfg = (Config) companyList.get(j);
						String tmpCompany = tmpCompanyCfg.getCFG_CODE();
						String content = getIntroUrl(prdExtList, prd, tmpLang, tmpCompany);
						xsb.startTagWithName("data", tmpCompanyCfg.getCFG_VALUE());
						xsb.appendEscape(content);
						xsb.endTag("data");
					}
					xsb.endTag("language");
				}
				xsb.endTag("introList");

				xsb.endTag("data");
			}
			xsb.endTag("datas");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("error in service", e);
			throw new RuntimeException(e);
		}
		return xsb.toString();
	}

	private String getPdfUrl(List prdExtList, Product prd, String tmpLang, String tmpCompany) {
		for (Iterator iterator = prdExtList.iterator(); iterator.hasNext();) {
			Config cfg = (Config) iterator.next();
			if (cfg.getCFG_TYPE().equals(Constant.CFG_TYPE_PDF)
					&& cfg.getCFG_CODE().equals(prd.getPRD_CODE() + Constant.CHAR_ + tmpCompany + Constant.CHAR_ + tmpLang)) {
				return cfg.getCFG_VALUE();
			}
		}
		return "";
	}

	private String getIntroUrl(List prdExtList, Product prd, String tmpLang, String tmpCompany) {
		for (Iterator iterator = prdExtList.iterator(); iterator.hasNext();) {
			Config cfg = (Config) iterator.next();
			if (cfg.getCFG_TYPE().equals(Constant.CFG_TYPE_INTRO)
					&& cfg.getCFG_CODE().equals(prd.getPRD_CODE() + Constant.CHAR_ + tmpCompany + Constant.CHAR_ + tmpLang)) {
				return cfg.getCFG_VALUE();
			}
		}
		return "";
	}

	private String getBuyUrl(List prdExtList, Product prd, String tmpLang, String tmpCompany) {
		for (Iterator iterator = prdExtList.iterator(); iterator.hasNext();) {
			Config cfg = (Config) iterator.next();
			if (cfg.getCFG_TYPE().equals(Constant.CFG_TYPE_BUYURL)
					&& cfg.getCFG_CODE().equals(prd.getPRD_CODE() + Constant.CHAR_ + tmpCompany + Constant.CHAR_ + tmpLang)) {
				return cfg.getCFG_VALUE();
			}
		}
		return "";
	}

	private String getFlv(List prdExtList, Product prd, String langCode) {
		for (Iterator iterator = prdExtList.iterator(); iterator.hasNext();) {
			Config cfg = (Config) iterator.next();
			if (cfg.getCFG_TYPE().equals(Constant.CFG_TYPE_FLV) && cfg.getCFG_CODE().equals(prd.getPRD_CODE() + Constant.CHAR_ + langCode)) {
				return cfg.getCFG_VALUE();
			}
		}
		return "";
	}

	public void setProductDAO(ProductDAO productDAO) {
		this.productDAO = productDAO;
	}

	public ProductDAO getProductDAO() {
		return productDAO;
	}

	public void setConfigDAO(ConfigDAO configDAO) {
		this.configDAO = configDAO;
	}

	public ConfigDAO getConfigDAO() {
		return configDAO;
	}

	/**
	 * no used
	 * 
	 * @param answers
	 * @param add
	 * @return
	 */
	public String tuijian_v01(String[] answers, String add) {
		XmlStringBuffer xsb = new XmlStringBuffer();
		List qaoptionList;
		LogicItem tuijianLogicItem = null;
		List prodList = null;
		try {
			{// GET all QAOPTION
				ConfigExample configExample = new ConfigExample();
				configExample.createCriteria().andCFG_TYPEEqualTo(Constant.CFG_TYPE_QAOPTION);
				qaoptionList = configDAO.selectByExample(configExample);
			}

			{// execute logic
				Set answerSet = new LinkedHashSet();
				for (int i = 0; i < answers.length; i++) {
					answerSet.add(answers[i]);
				}
				Logic logic = Constant.TUIJIAN_LOGIC;
				if (logic == null) {
					logger.error("System ERROR! No XML logic found or XML driver error!");
					throw new RuntimeException("System ERROR! No XML logic found or XML driver error!");
				}
				Assert.notNull(logic);
				LogicItem[] logics = logic.getLogics();
				LogicItem defaultlogic = logic.getDefaultLogic();
				boolean existLogic = false;
				for (int i = 0; i < logics.length; i++) {
					String ansers[] = logics[i].getAnswer();
					if (isMatch(answerSet, ansers)) {
						tuijianLogicItem = logics[i];
						existLogic = true;
						break;
					}
				}
				if (!existLogic) {
					tuijianLogicItem = defaultlogic;
				}
			}
			{// find the prd list to xml
				ProductExample example = new ProductExample();
				example.createCriteria().andPRD_TYPEEqualTo(tuijianLogicItem.getType1()).andPRD_REQUIREEqualTo(
						tuijianLogicItem.getRequire1()).andSHOW_FLGEqualTo(Constant.Y);
				example.createCriteria().andPRD_TYPEEqualTo(tuijianLogicItem.getType2()).andPRD_REQUIREEqualTo(
						tuijianLogicItem.getRequire2()).andSHOW_FLGEqualTo(Constant.Y);
				prodList = productDAO.selectByExample(example);

			}

			if (Constant.XML_HEAD_ISUSED) {
				xsb.appendOriginal(Constant.XML_HEAD_STRING);
			}
			xsb.startTag("datas");
			for (Iterator iterator = prodList.iterator(); iterator.hasNext();) {
				Product prd = (Product) iterator.next();
				xsb.startTag("id");
				xsb.appendEscape(prd.getPRD_CODE());
				xsb.endTag("id");
			}
			xsb.endTag("datas");

			{// insert answer
				Answer answer = new Answer();
				for (int ansIndex = 1; ansIndex <= 6; ansIndex++) {
					StringBuffer ansSb = new StringBuffer();
					for (int i = 0; i < answers.length; i++) {
						if (answers[i].startsWith(Constant.CHAR_QUESTIONSTART + ansIndex + Constant.CHAR_)) {
							for (Iterator iterator = qaoptionList.iterator(); iterator.hasNext();) {
								Config qaoption = (Config) iterator.next();
								if (qaoption.getCFG_CODE().equals(answers[i])) {
									ansSb.append(qaoption.getCFG_VALUE() + " ");
								}
							}
						}

					}
					setAnswerByIndex(answer, ansIndex, ansSb.toString());
				}
				answer.setANS_ID(getNextId());
				answer.setANS_ADDRESS(add);
				answer.setANS_DATE(Tools.getToday());
				answer.setANS_TIME(Tools.getTime());

				{// get prds
					StringBuffer tmpBuffer = new StringBuffer();
					for (Iterator iterator = prodList.iterator(); iterator.hasNext();) {
						Product prd = (Product) iterator.next();
						tmpBuffer.append(prd.getPRD_NAME() + " ");
					}
					answer.setANS_PRD(tmpBuffer.toString());
				}
				{// save QAOPTION id to freetext1
					StringBuffer tmpBuffer = new StringBuffer();
					for (int i = 0; i < answers.length; i++) {
						tmpBuffer.append(answers[i] + Constant.CHAR_CONNECT);
					}
					answer.setANS_FREETEXT1(shortStr(tmpBuffer.toString(), 180));
				}
				{// save prd id to freetext2
					StringBuffer tmpBuffer = new StringBuffer();
					for (Iterator iterator = prodList.iterator(); iterator.hasNext();) {
						Product prd = (Product) iterator.next();
						tmpBuffer.append(prd.getPRD_CODE() + Constant.CHAR_CONNECT);
					}

					answer.setANS_FREETEXT2(shortStr(tmpBuffer.toString(), 180));

				}

				answerDAO.insertSelective(answer);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("error in service", e);
			throw new RuntimeException(e);
		}

		return xsb.toString();
	}

	public String tuijian(String[] answers, String add) {
		XmlStringBuffer xsb = new XmlStringBuffer();
		List qaoptionList;
		List prodList = null;
		List logicList = new ArrayList();
		try {
			{// GET all QAOPTION
				ConfigExample configExample = new ConfigExample();
				configExample.createCriteria().andCFG_TYPEEqualTo(Constant.CFG_TYPE_QAOPTION);
				qaoptionList = configDAO.selectByExample(configExample);
			}

			{// execute logic
				Set answerSet = new LinkedHashSet();
				for (int i = 0; i < answers.length; i++) {
					if (answers[i] != null) {
						answerSet.add(answers[i].trim());
					}
				}

				// ~退休养老
				// If question1 ==步入中年 and question1 ==准备退休 and question4 包含
				// 为自已养老退休金
				if ((answerSet.contains("Q1_4") || answerSet.contains("Q1_5")) && answerSet.contains("Q4_1")) {
					// 退休养老 = 高
					logicList.add(new String[] { "TX", "H" });
					logger.debug("退休养老 = 高");
				}
				// ~少儿成长
				// If question1 == 已婚有未成年小孩 and question4 包含 计划孩子的健康和教育 then
				if (answerSet.contains("Q1_3") && answerSet.contains("Q4_2")) {
					// 少儿成长 = 高
					logicList.add(new String[] { "SE", "H" });
					logger.debug("少儿成长 = 高");
				}
				// ~意外健康
				// If (question1==单身 or question1==已婚没有小孩 or question1==已婚有未成年小孩
				// or question1==步入中年 or question1==准备退休) and
				// question3==状态良好喜欢旅游 and question4 包含 意外和医疗保障 then
				if ((answerSet.contains("Q1_1") || answerSet.contains("Q1_2") || answerSet.contains("Q1_3") || answerSet.contains("Q1_4") || answerSet
						.contains("Q1_5"))
						&& answerSet.contains("Q3_1") && answerSet.contains("Q4_3")) {
					// 意外健康 = 高
					logicList.add(new String[] { "YW", "H" });
					logger.debug("意外健康 = 高  TYPE1");

				} else
				// If (question1==已婚有未成年小孩 or question1==步入中年) and
				// question3==压力大不喜欢旅游 and question 4 包含 意外和医疗保障 then
				if ((answerSet.contains("Q1_3") || answerSet.contains("Q1_4")) && answerSet.contains("Q3_4") && answerSet.contains("Q4_3")) {
					// 意外健康 = 高
					logicList.add(new String[] { "YW", "H" });
					logger.debug("意外健康 = 高  TYPE2");
				} else
				// If (question1==单身 or question1==已婚没有小孩) and
				// question3=压力大不喜欢旅游 and question 4包含 意外和医疗保障 then
				if ((answerSet.contains("Q1_1") || answerSet.contains("Q1_2")) && answerSet.contains("Q3_4") && answerSet.contains("Q4_3")) {
					// 意外健康 = 中
					logicList.add(new String[] { "YW", "M" });
					logger.debug("意外健康 = 中");
				}

				// ~寿险重疾
				// If question1==已婚没有小孩 or question1==已婚有未成年小孩 or
				// question1==步入中年 and question4 包含 重大疾病和人寿保险 then
				if ((answerSet.contains("Q1_2") || answerSet.contains("Q1_3") || answerSet.contains("Q1_4")) && answerSet.contains("Q4_4")) {
					// 寿险重疾 = 高
					logicList.add(new String[] { "SX", "H" });
					logger.debug("寿险重疾 = 高");
				} else

				// If question1==单身 and question4 包含 重大疾病和人寿保险 then
				if (answerSet.contains("Q1_1") && answerSet.contains("Q4_4")) {
					// 寿险重疾 = 中
					logicList.add(new String[] { "SX", "M" });
					logger.debug("寿险重疾 = 中");
				}

				// ~投资理财
				// If question2 == 大于20000 and question4 包含 合理的理财规划 then
				if (answerSet.contains("Q2_3") && answerSet.contains("Q4_5")) {
					// 投资理财 = 高
					logicList.add(new String[] { "TZ", "H" });
					logger.debug("投资理财 = 高 TYPE1");
				} else
				// If question1 !=单身 and question2 = 8000-10000 and question4 包含
				// 合理的理财规划 then
				if (!answerSet.contains("Q1_1") && answerSet.contains("Q2_2") && answerSet.contains("Q4_5")) {
					// 投资理财 = 高
					logicList.add(new String[] { "TZ", "H" });
					logger.debug("投资理财 = 高 TYPE2");
				}
				if(logicList.size()==0){
					//寿险保障 需求=高
					//意外健康 需求=中
					logicList.add(new String[] { "SX", "H" });
					logicList.add(new String[] { "YW", "M" });
					logger.debug("默认：寿险保障 需求=高， 意外健康 需求=中");
				}

			}
			{              if(logicList.size()>0){
				                  ProductExample example = new ProductExample();
				                  int i = 0;
				                  for (Iterator iterator = logicList.iterator(); iterator.hasNext();) {
				                  	  i++;                     
				                  	  String[] arry = (String[]) iterator.next();                     
				                  	  ProductExample.Criteria criteria = example.createCriteria().andPRD_TYPEEqualTo(arry[0]).andPRD_REQUIREEqualTo(arry[1]);
				                  	  if (i > 1) {
				                  	  	    example.or(criteria);
				                  	  }
				                  }                  
				                  prodList = productDAO.selectByExample(example);
				             }else{                 
				             	    prodList =  new ArrayList();
				            }               
           }

			if (Constant.XML_HEAD_ISUSED) {
				xsb.appendOriginal(Constant.XML_HEAD_STRING);
			}
			xsb.startTag("datas");
			for (Iterator iterator = prodList.iterator(); iterator.hasNext();) {
				Product prd = (Product) iterator.next();
				xsb.startTag("id");
				xsb.appendEscape(prd.getPRD_CODE());
				xsb.endTag("id");
			}
			xsb.endTag("datas");
			
			/*
			{// insert answer
				Answer answer = new Answer();
				for (int ansIndex = 1; ansIndex <= 6; ansIndex++) {
					StringBuffer ansSb = new StringBuffer();
					for (int i = 0; i < answers.length; i++) {
						if (answers[i].startsWith(Constant.CHAR_QUESTIONSTART + ansIndex + Constant.CHAR_)) {
							for (Iterator iterator = qaoptionList.iterator(); iterator.hasNext();) {
								Config qaoption = (Config) iterator.next();
								if (qaoption.getCFG_CODE().equals(answers[i])) {
									ansSb.append(qaoption.getCFG_VALUE() + " ");
								}
							}
						}

					}
					setAnswerByIndex(answer, ansIndex, ansSb.toString());
				}
				answer.setANS_ID(getNextId());
				answer.setANS_ADDRESS(add);
				answer.setANS_DATE(Tools.getToday());
				answer.setANS_TIME(Tools.getTime());

				{// get prds
					StringBuffer tmpBuffer = new StringBuffer();
					for (Iterator iterator = prodList.iterator(); iterator.hasNext();) {
						Product prd = (Product) iterator.next();
						tmpBuffer.append(prd.getPRD_NAME() + " ");
					}
					answer.setANS_PRD(tmpBuffer.toString());
				}
				{// save QAOPTION id to freetext1
					StringBuffer tmpBuffer = new StringBuffer();
					for (int i = 0; i < answers.length; i++) {
						tmpBuffer.append(answers[i] + Constant.CHAR_CONNECT);
					}
					answer.setANS_FREETEXT1(shortStr(tmpBuffer.toString(), 180));
				}
				{// save prd id to freetext2
					StringBuffer tmpBuffer = new StringBuffer();
					for (Iterator iterator = prodList.iterator(); iterator.hasNext();) {
						Product prd = (Product) iterator.next();
						tmpBuffer.append(prd.getPRD_CODE() + Constant.CHAR_CONNECT);
					}

					answer.setANS_FREETEXT2(shortStr(tmpBuffer.toString(), 180));

				}

				answerDAO.insertSelective(answer);
			}
			*/
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("error in service", e);
			throw new RuntimeException(e);
		}

		return xsb.toString();
	}

	private String shortStr(String string, int i) {
		if (string == null || string.length() <= i) {
			return string;
		}
		if (string.length() > i) {
			return string.substring(0, 1);
		}
		return string;
	}

	private boolean isMatch(Set answerSet, String[] ansers) {
		if (answerSet == null || answerSet.size() == 0) {
			return false;
		}
		if (ansers == null || ansers.length == 0) {
			return false;
		}

		boolean toReturn = true;
		for (int i = 0; i < ansers.length; i++) {
			if (answerSet.contains(ansers[i])) {
				// ignore
			} else {
				toReturn = false;
				break;
			}
		}

		return toReturn;
	}

	private void setAnswerByIndex(Answer answer, int ansIndex, String string) {
		if (ansIndex == 1) {
			answer.setANS1(string);
		} else if (ansIndex == 2) {
			answer.setANS2(string);
		} else if (ansIndex == 3) {
			answer.setANS3(string);
		} else if (ansIndex == 4) {
			answer.setANS4(string);
		} else if (ansIndex == 5) {
			answer.setANS5(string);
		} else if (ansIndex == 6) {
			answer.setANS6(string);
		}

	}

	public void setAnswerDAO(AnswerDAO answerDAO) {
		this.answerDAO = answerDAO;
	}

	public AnswerDAO getAnswerDAO() {
		return answerDAO;
	}

	public void setSequenceDAO(SequenceDAO sequenceDAO) {
		this.sequenceDAO = sequenceDAO;
	}

	public SequenceDAO getSequenceDAO() {
		return sequenceDAO;
	}

	public void setSequenceNameProvider(SequenceNameProvider sequenceNameProvider) {
		this.sequenceNameProvider = sequenceNameProvider;
	}

	public SequenceNameProvider getSequenceNameProvider() {
		return sequenceNameProvider;
	}

	private synchronized Long getNextId() {
		String sequenceName = sequenceNameProvider.getName(Answer.class);
		Sequence seq = sequenceDAO.selectByPrimaryKey(sequenceName);
		seq.setNEXTID(new Long(seq.getNEXTID().longValue() + 1L));
		sequenceDAO.updateByPrimaryKey(seq);
		return seq.getNEXTID();
	}

	public String selectAllLink() {
		XmlStringBuffer xsb = new XmlStringBuffer();
		List linkList = null;
		int linkCount = 0;
		try {

			{
				ConfigExample configExample = new ConfigExample();
				configExample.createCriteria().andCFG_TYPEEqualTo(Constant.CFG_TYPE_LINK);
				configExample.setOrderByClause(Constant.ORDERBY_LINK);
				linkList = configDAO.selectByExample(configExample);
				linkCount = linkList.size();
				logger.debug("companyCount:" + linkCount);
			}

			if (Constant.XML_HEAD_ISUSED) {
				xsb.appendOriginal(Constant.XML_HEAD_STRING);
			}
			xsb.startTag("datas");
			for (int j = 0; j < linkCount; j++) {
				Config tmpCfg = (Config) linkList.get(j);
				xsb.startTagWithName("data", tmpCfg.getCFG_DESC());
				xsb.startTag("link");
				xsb.appendCDATA(tmpCfg.getCFG_VALUE());
				xsb.endTag("link");
				xsb.endTag("data");
			}
			xsb.endTag("datas");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("error in service", e);
			throw new RuntimeException(e);
		}
		return xsb.toString();
	}

	public String langVote(String langid) {
		if (logger.isDebugEnabled()) {
			logger.debug("langVote(String) - start"); //$NON-NLS-1$
		}

		Assert.notNull(langid);
		langid = langid.toUpperCase().trim();
		XmlStringBuffer xsb = new XmlStringBuffer();
		try {
			{
				ConfigKey key = new ConfigKey();
				key.setCFG_TYPE(Constant.CFG_TYPE_LANG);
				key.setCFG_CODE(langid);
				Config lang = configDAO.selectByPrimaryKey(key);
				if (lang != null) {
					logger.debug("langVote:" + lang.getCFG_VALUE());
					Long old = lang.getCFG_FREENUM1();
					Long new_count = null;
					if (old == null) {
						new_count = new Long(1);
					} else {
						new_count = new Long(old.intValue() + 1);
					}
					logger.debug("langVote_old:" + old);
					logger.debug("langVote_new:" + new_count);
					lang.setCFG_FREENUM1(new_count);
					configDAO.updateByPrimaryKeySelective(lang);
				} else {
					logger.debug("langVote, lang not found >" + langid);

				}

			}

			if (Constant.XML_HEAD_ISUSED) {
				xsb.appendOriginal(Constant.XML_HEAD_STRING);
			}
			xsb.startTag("datas");
			xsb.appendEscape("success");
			xsb.endTag("datas");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("error in service", e);
			throw new RuntimeException(e);
		}
		String returnString = xsb.toString();
		if (logger.isDebugEnabled()) {
			logger.debug("langVote(String) - end"); //$NON-NLS-1$
		}
		return returnString;
	}

	public String buyVote(String productid, String companyid, String langid) {

		Assert.notNull(productid);
		Assert.notNull(companyid);
		Assert.notNull(langid);

		XmlStringBuffer xsb = new XmlStringBuffer();
		try {
			{
				ConfigKey key = new ConfigKey();
				key.setCFG_TYPE(Constant.CFG_TYPE_BUYURL);
				// AIO_C1_L1
				key.setCFG_CODE(productid + Constant.CHAR_ + companyid + Constant.CHAR_ + langid);
				Config lang = configDAO.selectByPrimaryKey(key);
				if (lang != null) {
					logger.debug("buyVote:" + lang.getCFG_VALUE());
					Long old = lang.getCFG_FREENUM1();
					Long new_count = null;
					if (old == null) {
						new_count = new Long(1);
					} else {
						new_count = new Long(old.intValue() + 1);
					}
					logger.debug("buyVote_old:" + old);
					logger.debug("buyVote_new:" + new_count);
					lang.setCFG_FREENUM1(new_count);
					configDAO.updateByPrimaryKeySelective(lang);
				} else {
					logger.debug("buyVote, record not found >" + productid + Constant.CHAR_ + companyid + Constant.CHAR_ + langid);

				}

			}

			if (Constant.XML_HEAD_ISUSED) {
				xsb.appendOriginal(Constant.XML_HEAD_STRING);
			}
			xsb.startTag("datas");
			xsb.appendEscape("success");
			xsb.endTag("datas");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("error in service", e);
			throw new RuntimeException(e);
		}
		String returnString = xsb.toString();
		return returnString;
	}

	public String getproduct(String id) {
		XmlStringBuffer xsb = new XmlStringBuffer();
		try {
			if (Constant.XML_HEAD_ISUSED) {
				xsb.appendOriginal(Constant.XML_HEAD_STRING);
			}
			xsb.startTag("datas");
			xsb.startTag("id");
			xsb.appendEscape(id);
			xsb.endTag("id");
			xsb.endTag("datas");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("error in service", e);
			throw new RuntimeException(e);
		}
		String returnString = xsb.toString();
		return returnString;
	} 
	
	public String flvVote(String productid, String langid) {

		Assert.notNull(productid);
		Assert.notNull(langid);

		XmlStringBuffer xsb = new XmlStringBuffer();
		try {
			{
				ConfigKey key = new ConfigKey();
				key.setCFG_TYPE(Constant.CFG_TYPE_FLV);
				// AIO_L1
				key.setCFG_CODE(productid + Constant.CHAR_ + langid);
				Config lang = configDAO.selectByPrimaryKey(key);
				if (lang != null) {
					logger.debug("flvVote:" + lang.getCFG_VALUE());
					Long old = lang.getCFG_FREENUM1();
					Long new_count = null;
					if (old == null) {
						new_count = new Long(1);
					} else {
						new_count = new Long(old.intValue() + 1);
					}
					logger.debug("flvVote_old:" + old);
					logger.debug("flvVote_new:" + new_count);
					lang.setCFG_FREENUM1(new_count);
					configDAO.updateByPrimaryKeySelective(lang);
				} else {
					logger.debug("flvVote, record not found >" + productid  + Constant.CHAR_ + langid);
				}

			}

			if (Constant.XML_HEAD_ISUSED) {
				xsb.appendOriginal(Constant.XML_HEAD_STRING);
			}
			xsb.startTag("datas");
			xsb.appendEscape("success");
			xsb.endTag("datas");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("error in service", e);
			throw new RuntimeException(e);
		}
		String returnString = xsb.toString();
		return returnString;
	}

	public String selectLimitNews(int limit) {
		if (limit <= 0) {
			limit = Constant.MAX_COUNT_WHEN_EXCEPTION;
		}
		XmlStringBuffer xsb = new XmlStringBuffer();
		List linkList = null;
		int linkCount = 0;
		try {

			{
				ConfigExample configExample = new ConfigExample();
				configExample.createCriteria().andCFG_TYPEEqualTo(Constant.CFG_TYPE_NEWS);
				configExample.setOrderByClause(Constant.ORDERBY_NEWS);
				linkList = configDAO.selectByExample(configExample, 0, limit);
				linkCount = linkList.size();
				logger.debug("news:" + linkCount);
			}

			if (Constant.XML_HEAD_ISUSED) {
				xsb.appendOriginal(Constant.XML_HEAD_STRING);
			}
			xsb.startTag("datas");
			for (int j = 0; j < linkCount; j++) {
				xsb.startTag("data");
				Config tmpCfg = (Config) linkList.get(j);
				xsb.startTag("id");
				xsb.appendEscape(tmpCfg.getCFG_CODE());
				xsb.endTag("id");
				xsb.startTag("title");
				xsb.appendEscape(tmpCfg.getCFG_VALUE());
				xsb.endTag("title");
				xsb.startTag("time");
				String dateFromDB = tmpCfg.getCFG_DATE();
				String dateFormated = Tools.date8todate10(dateFromDB);
				xsb.appendEscape(dateFormated);
				xsb.endTag("time");				
				xsb.endTag("data");
			}
			xsb.endTag("datas");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("error in service", e);
			throw new RuntimeException(e);
		}
		return xsb.toString();
	}

	public String getNewsContent(String id) {
		XmlStringBuffer xsb = new XmlStringBuffer();
		Config tmpCfg = null;
		try {
			{
				ConfigExample configExample = new ConfigExample();
				configExample.createCriteria().andCFG_TYPEEqualTo(Constant.CFG_TYPE_NEWS).andCFG_CODEEqualTo(id);
				configExample.setOrderByClause(Constant.ORDERBY_NEWS);
				ConfigKey key = new ConfigKey();
				key.setCFG_CODE(id);
				key.setCFG_TYPE(Constant.CFG_TYPE_NEWS);
				tmpCfg = configDAO.selectByPrimaryKey(key);
			}

			if (Constant.XML_HEAD_ISUSED) {
				xsb.appendOriginal(Constant.XML_HEAD_STRING);
			}
			if (tmpCfg != null) {
				xsb.startTag("datas");
				xsb.startTag("id");
				xsb.appendEscape(tmpCfg.getCFG_CODE());
				xsb.endTag("id");
				xsb.startTag("title");
				xsb.appendEscape(tmpCfg.getCFG_VALUE());
				xsb.endTag("title");
				xsb.startTag("time");
				String dateFromDB = tmpCfg.getCFG_DATE();
				String dateFormated = Tools.date8todate10(dateFromDB);
				xsb.appendEscape(dateFormated);
				xsb.endTag("time");
				xsb.startTag("cont");
				xsb.appendEscape(tmpCfg.getCFG_FREETEXT3());
				xsb.endTag("cont");
				xsb.endTag("datas");
			} else {
				xsb.startTag("datas");
				xsb.appendEscape("error");
				xsb.endTag("datas");
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error("error in service", e);
			throw new RuntimeException(e);
		}
		return xsb.toString();
	}

	public String custreg(String[] answers, String add, String imageSession, String image, String name, String city, String mobile,
			String email, String prcid, String agreeflg, String company, String from, String town) {
		XmlStringBuffer xsb = new XmlStringBuffer();
		List qaoptionList;
		List prodList = null;
		List logicList = new ArrayList();
		boolean success = true;
		String returncode="00";
		String returndesc="成功";
		try {
			
			{// validation
				if (success) {
					if (imageSession != null && image != null && !image.trim().equalsIgnoreCase(Constant.CAPTCHA_SESSION_INIT_VALUE)
							&& imageSession.equalsIgnoreCase(image)) {
						//
					} else {
						success = false;
						returncode = "01";
						returndesc = "没有正确填写验证码";
					}
				}
				if (success) {
					if (prcid == null || prcid.trim().length() == 0) {
						success = false;
						returncode = "31";
						returndesc = "身份证号格式不正确";
					} else {
						prcid = prcid.trim();
					}
				}
				
				if (success) {
					IdcardValidator iv = new IdcardValidator();
					if (!iv.isValidatedAllIdcard(prcid)) {
						success = false;
						returncode = "31";
						returndesc = "身份证号格式不正确";
					} else {
						prcid = prcid.trim();
					}
				}
				
				
				if(success){//验证该身份证号是否参加过活动
					AnswerExample exampleValidate = new AnswerExample();
					exampleValidate.createCriteria().andANS_PRCIDEqualTo(prcid);
					List records = answerDAO.selectByExample(exampleValidate );
					if(records!=null && records.size()>0){
						success = false;
						returncode = "20";
						returndesc = "该身份证号已经参加过活动";
					}
				}
				
				if (success) {
					if (name == null || name.trim().length() == 0) {
						success = false;
						returncode = "32";
						returndesc = "姓名格式不正确";
					} else {
						name = name.trim();
					}
				}
				
				if (success) {
					if (city == null || city.trim().length() == 0) {
						success = false;
						returncode = "34";
						returndesc = "城市代码格式不正确";
					} else {
						city = city.trim();
					}
				}
				
				if (success) {
					if (email == null || email.trim().length() == 0) {
						success = false;
						returncode = "35";
						returndesc = "Email格式不正确";
					} else {
						email = email.trim();
					}
				}
				
				if (success) {
					if (agreeflg == null || agreeflg.trim().length() != 1) {
						success = false;
						returncode = "36";
						returndesc = "钩选格式不正确";
					} else {
						agreeflg = agreeflg.trim();
					}
				}
				
				if (success) {
					if (mobile == null || mobile.trim().length() ==0) {
						success = false;
						returncode = "37";
						returndesc = "手机号格式不正确";
					} else {
						mobile = mobile.trim();
					}
				}
				
				if (success) {
					if (company == null || company.trim().length() ==0) {
						success = false;
						returncode = "38";
						returndesc = "分公司代码格式不正确";
					} else {
						company = company.trim();
					}
				}
			}
			
			if (success) {
				{// GET all QAOPTION
					ConfigExample configExample = new ConfigExample();
					configExample.createCriteria().andCFG_TYPEEqualTo(Constant.CFG_TYPE_QAOPTION);
					qaoptionList = configDAO.selectByExample(configExample);
				}

				{// execute logic
					Set answerSet = new LinkedHashSet();
					for (int i = 0; i < answers.length; i++) {
						if (answers[i] != null) {
							answerSet.add(answers[i].trim());
						}
					}

					// ~退休养老
					// If question1 ==步入中年 and question1 ==准备退休 and question4 包含
					// 为自已养老退休金
					if ((answerSet.contains("Q1_4") || answerSet.contains("Q1_5")) && answerSet.contains("Q4_1")) {
						// 退休养老 = 高
						logicList.add(new String[] { "TX", "H" });
						logger.debug("退休养老 = 高");
					}
					// ~少儿成长
					// If question1 == 已婚有未成年小孩 and question4 包含 计划孩子的健康和教育 then
					if (answerSet.contains("Q1_3") && answerSet.contains("Q4_2")) {
						// 少儿成长 = 高
						logicList.add(new String[] { "SE", "H" });
						logger.debug("少儿成长 = 高");
					}
					// ~意外健康
					// If (question1==单身 or question1==已婚没有小孩 or
					// question1==已婚有未成年小孩
					// or question1==步入中年 or question1==准备退休) and
					// question3==状态良好喜欢旅游 and question4 包含 意外和医疗保障 then
					if ((answerSet.contains("Q1_1") || answerSet.contains("Q1_2") || answerSet.contains("Q1_3")
							|| answerSet.contains("Q1_4") || answerSet.contains("Q1_5"))
							&& answerSet.contains("Q3_1") && answerSet.contains("Q4_3")) {
						// 意外健康 = 高
						logicList.add(new String[] { "YW", "H" });
						logger.debug("意外健康 = 高  TYPE1");

					} else
					// If (question1==已婚有未成年小孩 or question1==步入中年) and
					// question3==压力大不喜欢旅游 and question 4 包含 意外和医疗保障 then
					if ((answerSet.contains("Q1_3") || answerSet.contains("Q1_4")) && answerSet.contains("Q3_4")
							&& answerSet.contains("Q4_3")) {
						// 意外健康 = 高
						logicList.add(new String[] { "YW", "H" });
						logger.debug("意外健康 = 高  TYPE2");
					} else
					// If (question1==单身 or question1==已婚没有小孩) and
					// question3=压力大不喜欢旅游 and question 4包含 意外和医疗保障 then
					if ((answerSet.contains("Q1_1") || answerSet.contains("Q1_2")) && answerSet.contains("Q3_4")
							&& answerSet.contains("Q4_3")) {
						// 意外健康 = 中
						logicList.add(new String[] { "YW", "M" });
						logger.debug("意外健康 = 中");
					}

					// ~寿险重疾
					// If question1==已婚没有小孩 or question1==已婚有未成年小孩 or
					// question1==步入中年 and question4 包含 重大疾病和人寿保险 then
					if ((answerSet.contains("Q1_2") || answerSet.contains("Q1_3") || answerSet.contains("Q1_4"))
							&& answerSet.contains("Q4_4")) {
						// 寿险重疾 = 高
						logicList.add(new String[] { "SX", "H" });
						logger.debug("寿险重疾 = 高");
					} else

					// If question1==单身 and question4 包含 重大疾病和人寿保险 then
					if (answerSet.contains("Q1_1") && answerSet.contains("Q4_4")) {
						// 寿险重疾 = 中
						logicList.add(new String[] { "SX", "M" });
						logger.debug("寿险重疾 = 中");
					}

					// ~投资理财
					// If question2 == 大于20000 and question4 包含 合理的理财规划 then
					if (answerSet.contains("Q2_3") && answerSet.contains("Q4_5")) {
						// 投资理财 = 高
						logicList.add(new String[] { "TZ", "H" });
						logger.debug("投资理财 = 高 TYPE1");
					} else
					// If question1 !=单身 and question2 = 8000-10000 and
					// question4 包含
					// 合理的理财规划 then
					if (!answerSet.contains("Q1_1") && answerSet.contains("Q2_2") && answerSet.contains("Q4_5")) {
						// 投资理财 = 高
						logicList.add(new String[] { "TZ", "H" });
						logger.debug("投资理财 = 高 TYPE2");
					}
					if (logicList.size() == 0) {
						// 寿险保障 需求=高
						// 意外健康 需求=中
						logicList.add(new String[] { "SX", "H" });
						logicList.add(new String[] { "YW", "M" });
						logger.debug("默认：寿险保障 需求=高， 意外健康 需求=中");
					}

				}
				{
					if (logicList.size() > 0) {
						ProductExample example = new ProductExample();
						int i = 0;
						for (Iterator iterator = logicList.iterator(); iterator.hasNext();) {
							i++;
							String[] arry = (String[]) iterator.next();
							ProductExample.Criteria criteria = example.createCriteria().andPRD_TYPEEqualTo(arry[0]).andPRD_REQUIREEqualTo(
									arry[1]);
							if (i > 1) {
								example.or(criteria);
							}
						}
						prodList = productDAO.selectByExample(example);
					} else {
						prodList = new ArrayList();
					}
				}


				{// insert answer
					Answer answer = new Answer();
					for (int ansIndex = 1; ansIndex <= 6; ansIndex++) {
						StringBuffer ansSb = new StringBuffer();
						for (int i = 0; i < answers.length; i++) {
							if (answers[i].startsWith(Constant.CHAR_QUESTIONSTART + ansIndex + Constant.CHAR_)) {
								for (Iterator iterator = qaoptionList.iterator(); iterator.hasNext();) {
									Config qaoption = (Config) iterator.next();
									if (qaoption.getCFG_CODE().equals(answers[i])) {
										ansSb.append(qaoption.getCFG_VALUE() + " ");
									}
								}
							}

						}
						setAnswerByIndex(answer, ansIndex, ansSb.toString());
					}
					answer.setANS_ID(getNextId());
					answer.setANS_ADDRESS(add);
					answer.setANS_DATE(Tools.getToday());
					answer.setANS_TIME(Tools.getTime());

					{// get prds
						StringBuffer tmpBuffer = new StringBuffer();
						for (Iterator iterator = prodList.iterator(); iterator.hasNext();) {
							Product prd = (Product) iterator.next();
							tmpBuffer.append(prd.getPRD_NAME() + " ");
						}
						answer.setANS_PRD(tmpBuffer.toString());
					}
					{// save QAOPTION id to freetext1
						StringBuffer tmpBuffer = new StringBuffer();
						for (int i = 0; i < answers.length; i++) {
							tmpBuffer.append(answers[i] + Constant.CHAR_CONNECT);
						}
						answer.setANS_FREETEXT1(shortStr(tmpBuffer.toString(), 180));
					}
					{// save prd id to freetext2
						StringBuffer tmpBuffer = new StringBuffer();
						for (Iterator iterator = prodList.iterator(); iterator.hasNext();) {
							Product prd = (Product) iterator.next();
							tmpBuffer.append(prd.getPRD_CODE() + Constant.CHAR_CONNECT);
						}

						answer.setANS_FREETEXT2(shortStr(tmpBuffer.toString(), 180));

					}
					
					answer.setANS_EMAIL(email);
					answer.setANS_CITY(city);
					answer.setANS_MOBILE(mobile);
					answer.setANS_PRCID(prcid);
					answer.setANS_NAME(name);
					answer.setANS_EMAIL(email);
					answer.setANS_AGREE_FLG(agreeflg);
					answer.setANS_FREETEXT3(company);
					answer.setANS_FREETEXT4(Constant.ANSWER_SOURCE);
					//answer.setANS_FREETEXT5(Tools.getTodayDiff(Constant.ANSWER_DIFF_DAYS));
					answer.setANS_FREETEXT5("5");
					answer.setANS_FREETEXT6(from);
					answer.setANS_FREETEXT7(Constant.ANSWER_REQUIRE);
					answer.setANS6(town);
					answerDAO.insertSelective(answer);
					if (logger.isDebugEnabled()) {
						logger.debug("name=" + name + ",city=" + city + ",prcid=" + prcid);
					}
				}
			}
		} catch (Exception e) {
			success = false;
			returncode = "99";
			returndesc = "系统错误";
			e.printStackTrace();
			logger.error("error in service", e);
			throw new RuntimeException(e);
		} finally {
			xsb.startTag("datas");
			xsb.startTag("success");
			if (success) {
				xsb.appendEscape("true");
			} else {
				xsb.appendEscape("false");
			}
			xsb.endTag("success");
			xsb.startTag("returncode");
			xsb.appendEscape(returncode);
			xsb.endTag("returncode");
			xsb.startTag("returndesc");
			xsb.appendEscape(returndesc);
			xsb.endTag("returndesc");
			xsb.endTag("datas");
		}

		return xsb.toString();
	}

}
